//
//  JSSegmentedControlCell.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/20.
//

import UIKit

/// 分段选择
class JSSegmentedControlCell: JSBaseViewCell
{
//    let items = ["选项一"]
    lazy var segmented:UISegmentedControl = {
        var _segmented = UISegmentedControl()
        _segmented.selectedSegmentIndex = 1 //默认选中第二项
        _segmented.addTarget(self, action: #selector(segmentDidchange(_:)),for: .valueChanged) //添加值改变监听
        return _segmented
    }()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.addSubview(self.segmented)
        self.segmented.snp.makeConstraints { (make) in
            make.right.equalTo(-self.cellMargin);
            make.centerY.equalTo(self.contentView.snp.centerY);
        }
    }
    //选项除了文字还可以是图片
    @objc func segmentDidchange(_ segmented:UISegmentedControl){
        //获得选项的索引
        print(segmented.selectedSegmentIndex)
        //获得选择的文字
        print(segmented.titleForSegment(at: segmented.selectedSegmentIndex)!)
        let title = segmented.titleForSegment(at: segmented.selectedSegmentIndex)!
        model.text = title
        self.parentVC.uploadDict[self.model.key!] = title
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func initWith<T>(Model formModel: JSFormModel, VC ViewController: T) where T : BaseFormsController {
        super.initWith(Model: formModel, VC: ViewController)
//        segmented.removeAllSegments()
        for (index,item) in self.model.items.enumerated() {
            if segmented.numberOfSegments<self.model.items.count {
                segmented.insertSegment(withTitle: item.name, at: index, animated: true)
            }
        }
        
        if model.text.count>0 {
            segmented.selectedSegmentIndex = self.model.items.firstIndex { $0.name == model.text }!
        }else
        {
            self.segmented.selectedSegmentIndex = self.model.items.firstIndex { $0.selected == true }!
        }
    }
}
